<?php
/*
 * @Date: 2020-05-03 22:03:52
 * @名称: 
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2020-08-17 22:11:24
 * @FilePath: /服务器/app/serverLocalhost/controller/Edit.php
 */

namespace app\serverLocalhost\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\View;

class Edit extends BaseController
{
    public function EditProject()
    {
        $bookId =  input("post.bookId");
        $projectId =  input("post.projectId");
        $time =  time();

        /*  $bookId =  "58218e5a5f6b9a4f93e242bb";
        $projectId =  "58218e605f6b9a4f93e244c1"; */
        $hashHmac_bookId = hash_hmac("sha256", $bookId . $time, config("globalsettings.serverLocalhost_Edit_sha256Encryption")); //加密后
        $hashHmac_projectId = hash_hmac("sha256", $projectId . $time, config("globalsettings.serverLocalhost_Edit_sha256Encryption")); //加密后
        $project_info =  Db::table('book_info_project')
            ->where([
                "_id" => $bookId,
                "chapter_id" => $projectId,
            ])
            ->field([
                "project_title",
                "order",
                "database_table_name",
            ])
            ->select();
        $tableName = base64_encode(authcode($project_info[0]['database_table_name'], "encode", $bookId . $projectId . $time)); //图片要插入的表的名字
        if (count($project_info) > 1) {
            return view('ErrorPage/Error', [
                "errorCode" => 2006,
                "errorTitle" => "发生严重错误",
                "errorMsg" => "这一个漫画id对应多个漫画请尝试修复 这是不允许的操作",
            ]);
        }
        if (count($project_info) < 1) {
            return view('ErrorPage/Error', [
                "errorCode" => 2007,
                "errorTitle" => "发生严重错误",
                "errorMsg" => "为检索到漫画信息",
            ]);
        }
        View::assign('serverLocalhost', "serverLocalhost");
        return view('Edit/EditProject/EditProject', [
            "projectTitle" => $project_info[0]['project_title'],
            "projectOrder" => $project_info[0]['order'],
            "serverLocalhost" => config("globalsettings.serverLocalhost_serverHost"),
            "time" => $time,
            "hashHmac_bookId" => $hashHmac_bookId,
            "hashHmac_projectId" => $hashHmac_projectId,
            "bookId" => $bookId,
            "projectId" => $projectId,
            "image_sever" => config("globalsettings.image_sever"),
            "database_table_name" =>  $tableName,
        ]);
    }
    public function getImagesList()
    {
        $time = input('post.time'); //@ 时间戳
        $encryption_bookId = input('post.encryption_bookId'); //@ 书籍id 加密后
        $encryption_projectId = input('post.encryption_projectId'); //@ 章节id 加密后
        $bookId = input('post.bookId'); //@ 书籍id 加密前
        $projectId = input('post.projectId'); //@ 章节id 加密前
        /*   $time = "1595577314";
        $encryption_bookId = "716e7cefb9d5da18b246f3468e8434d74a1c80de6969f5f295ccd48cc393ca22";
        $encryption_projectId = "d6bbc732177373d6ec73b8e6027c4964c72838dbe55dae79da29be6cb7b79a2a";
        $bookId = "582186a35f6b9a4f93dcb549";
        $projectId = "582186a35f6b9a4f93dcb54b"; */

        $hashHmac_bookId = hash_hmac("sha256", $bookId . $time, config("globalsettings.serverLocalhost_Edit_sha256Encryption")); //加密后
        $hashHmac_projectId = hash_hmac("sha256", $projectId . $time, config("globalsettings.serverLocalhost_Edit_sha256Encryption")); //加密后
        if ( //判断加密验证是否一样
            $time &&
            $encryption_bookId &&
            $encryption_projectId &&
            $bookId &&
            $projectId &&
            $encryption_bookId ==
            $hashHmac_bookId &&
            $encryption_projectId ==
            $hashHmac_projectId
        ) {
            if ($time + 60 > time()) {
                $project_info =  Db::table('book_info_project')
                    ->where([
                        "_id" => $bookId,
                        "chapter_id" => $projectId,
                    ])
                    ->field([
                        "database_table_name" //图片所在数据库
                    ])
                    ->select();

                if (count($project_info) > 1) {
                    return errorJsonReturn("Comics-10000");
                }
                if (count($project_info) < 1) {
                    return errorJsonReturn("Comics-10001");
                }
                //# 判断是否没有分配漫画表 
                $tableName = "";
                if (!$project_info[0]["database_table_name"]) {
                    //#没有分配 分卷表 查询 可以分配的
                    $insertTable = Db::table('setting')
                        ->where([
                            "id" => 1
                        ])
                        ->field("images_insert_table_name")
                        ->find();


                    $tableCount = Db::table("$insertTable[images_insert_table_name]")
                        ->count();

                    if ($tableCount > 48000) {
                        $insertTable["images_insert_table_name"]++;
                        Db::table('setting')
                            ->where([
                                "id" => 1
                            ])
                            ->update([
                                "images_insert_table_name" => $insertTable["images_insert_table_name"],
                            ]);
                    }
                    $tableName = $insertTable["images_insert_table_name"];
                    Db::table('book_info_project')
                        ->where([
                            "_id" => $bookId,
                            "chapter_id" => $projectId,
                        ])
                        ->update([
                            "database_table_name" => $insertTable["images_insert_table_name"], //图片所在数据库
                        ]);
                } else {
                    $tableName = $project_info[0]["database_table_name"];
                }
                $tempComicsImagesList = Db::table($tableName)
                    ->where([
                        "_id" => $bookId,
                        "project_id" => $projectId,
                    ])
                    ->field([
                        "frame_id",
                        "original_name",
                        "image_server_host",
                    ])
                    ->select();
                return successJsonReturn(["list" => $tempComicsImagesList, "service" =>  $tableName]);
            } else {
                return errorJsonReturn("Other-10000");
            }
        } else {
            return errorJsonReturn("Other-10002");
        }
    }
    public function SubmissionProjectData() //提交章节数据
    {
        $projectName = input('post.projectName'); //@ 分卷名称
        $subsection = input('post.subsection'); //@ 分卷编号
        $time = input('post.time'); //@ 时间戳
        $encryption_bookId = input('post.encryption_bookId'); //@ 书籍id 加密后
        $encryption_projectId = input('post.encryption_projectId'); //@ 章节id 加密后
        $bookId = input('post.bookId'); //@ 书籍id 加密前
        $projectId = input('post.projectId'); //@ 章节id 加密前
        $imageList = input('post.imageList'); //@ 图片列表
        $hashHmac_bookId = hash_hmac("sha256", $bookId . $time, config("globalsettings.serverLocalhost_Edit_sha256Encryption")); //加密后
        $hashHmac_projectId = hash_hmac("sha256", $projectId . $time, config("globalsettings.serverLocalhost_Edit_sha256Encryption")); //加密后
        //记数类
        $removeNameCount = 0; //统计改名字的文件
        $deleteCount = 0; //统计改名字的文件
        $errorCount = 0; //出现错误统计
        $isOrder = true; //出现错误统计
        if ( //判断加密验证是否一样
            $projectName &&
            $subsection &&
            $time &&
            $encryption_bookId &&
            $encryption_projectId &&
            $bookId &&
            $projectId &&
            $imageList &&
            $encryption_bookId ==
            $hashHmac_bookId &&
            $encryption_projectId ==
            $hashHmac_projectId
        ) {
            if ($time + 3600 > time()) {
                $project_info =  Db::table('book_info_project')
                    ->where([
                        "_id" => $bookId,
                        "chapter_id" => $projectId,
                    ])
                    ->field([
                        "database_table_name", //图片所在数据库
                        "order", //查询分卷信息
                        "project_title", //查询标题
                    ])
                    ->select();

                if (count($project_info) > 1) {
                    return errorJsonReturn("Comics-10000");
                }
                if (count($project_info) < 1) {
                    return errorJsonReturn("Comics-10001");
                }
                //!判断 是否修改了基本信息
                if ($project_info[0]['order'] != $subsection) {
                    //#更新分卷序列
                    $order =  Db::table('book_info_project')
                        ->where([
                            "_id" => $bookId,
                            "order" => $subsection,
                        ])
                        ->find();
                    if ($order) {
                        $isOrder = false;
                    } else {
                        Db::table('book_info_project')
                            ->where([
                                "_id" => $bookId,
                                "chapter_id" => $projectId,
                            ])
                            ->update([
                                "order" => $subsection,
                            ]);
                        $isOrder = true;
                    }
                }

                if ($project_info[0]['project_title'] != $projectName) {
                    Db::table('book_info_project')
                        ->where([
                            "_id" => $bookId,
                            "chapter_id" => $projectId,
                        ])
                        ->update([
                            "project_title" => $projectName,
                        ]);
                }

                //!更新 漫画信息
                $database_name = $project_info[0]['database_table_name'];
                $tempComicsProjectList = Db::table($database_name) //查询全部图片 当前章节的
                    ->where([
                        "_id" => $bookId,
                        "project_id" => $projectId,
                    ])
                    ->select();
                $mysqlDataList = [];
                foreach ($tempComicsProjectList as $key => $value) {
                    unset($value['id']);
                    $mysqlDataList[$value['frame_id']]  = $value;
                }
                Db::table($database_name) //查询全部图片 当前章节的
                    ->where([
                        "_id" => $bookId,
                        "project_id" => $projectId,
                    ])
                    ->delete();
                foreach ($imageList as $key => $value) { //更新数据
                    if (isset($mysqlDataList[$value['imagesId']])) {
                        if ($mysqlDataList[$value['imagesId']]['original_name'] != $value['filename']) {
                            $mysqlDataList[$value['imagesId']]['original_name'] = $value['filename'];
                            $removeNameCount++;
                        }
                        Db::table($database_name)
                            ->insert($mysqlDataList[$value['imagesId']]);
                        unset($mysqlDataList[$value['imagesId']]);
                    } else {
                        $errorCount++; //出现错误统计
                    }
                }
                $deleteCount = count($mysqlDataList);



                return successJsonReturn([
                    "removeNameCount" => $removeNameCount,
                    "deleteCount" => $deleteCount,
                    "errorCount" => $errorCount,
                    "isOrder" => $isOrder,
                ]);
            } else {
                return errorJsonReturn("Other-10000"); //超时
            }
        } else {
            return errorJsonReturn("Comics-10002"); //超时
        }
    }
    /**
     * 编辑漫画信息
     * @param post bookId
     * @return void
     */
    public function EditComicsInfo()
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        //    dump($userTokenVerificationParse);

        $time =  time();
        $bookId =  input('post.bookId');
        // $bookId =  "book-pasbsr-r64gie46tenrzee33wpmkap8wp1u6umop0segvnfdaugflkwsxcz5jxbjtzxcxyflim2e38pz6ufxuekp4ssxkarc3cnce9ojmwbuf6v41imb9cwo0jb";
        $hashHmac_bookId = hash_hmac("sha256", $bookId . $time, config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后 加密id
        $hashHmac_toKen = hash_hmac("sha256", $token . $bookId . $time, config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后 加密id
        $book_info = Db::table('book_info')
            ->alias('book_info')
            ->join("book_list book_list", "book_list._id=book_info._id")
            ->where([
                "book_info._id" => $bookId,
            ])
            ->field([
                "book_list.title",
                #标题
                "book_list.original_name",
                #保存文件名字
                "book_list.path",
                #路径
                "book_list.file_server",
                #服务器地址
                "book_info.categories",
                #分类
                "book_info.tags",
                #标签
                "book_info.description",
                #简介
                "book_info.allow_download",
                #是否允许下载
                "book_info.allow_comment",
                #是否允许评论
            ])
            ->select(); //查询这个漫画的数据

        if (count($book_info) == 1) {
            $book_info = $book_info[0];
            $book_info['author_and_chinese_team'] = Db::table('author_and_chinese_team') //如果就一条数据 就开始查询作者
                ->alias('author_and_chinese_team')
                // ->leftJoin('user_info author', 'author._id = author_and_chinese_team.author_id')
                ->leftJoin('user_info user_info', 'user_info._id = author_and_chinese_team.user_id')
                ->where(
                    [
                        "author_and_chinese_team.book_id" => $bookId,
                    ]
                )
                ->field([
                    'author_and_chinese_team.author_or_chinese_team', //作者表 协作者1 / 创建者0
                    'author_and_chinese_team.state', //状态 0正常 1 新加入待漫画作者审核 2漫画作者审核未通过 3自己退出项目 4协作者请求删除协作者 5代漫画作者审核 6已删除
                    'author_and_chinese_team._id', //列表id
                    'author_and_chinese_team.exp_state', //用户权限信息 
                    'author_and_chinese_team.edit_delete_user', //是否允许删除用户 
                    'author_and_chinese_team.edit_inherit_users', //是否允许继承用户
                    'author_and_chinese_team.edit_add_user', //是否允许 新增用户
                    'author_and_chinese_team.edit_sever_comics_info', //是否允许 保存修改漫画信息
                    'user_info._id as user_id', //用户表 协作者1 / 创建者0
                    'user_info.user_name as user_name', //用户表 用户名
                ])
                ->select()->toArray();

            $book_info['me_role'] = 'other'; //初始化定义我的角色为其他
            foreach ($book_info['author_and_chinese_team'] as $key => $value) {
                if ($value['state'] == 1 && $value['user_id'] == $user_info["_id"]) {
                    switch ($value['exp_state']) {
                        case 8:
                            $errorCode = '104';
                            $errorMsg = '已自行提交用户权限';
                            break;
                        case 2:
                            $errorCode = '105';
                            $errorMsg = '已被漫画作者移除';
                            break;
                        case 7:
                            $errorCode = '106';
                            $errorMsg = '您自己已退出漫画项目';
                            break;
                        case 11:
                            $errorCode = '107';
                            $errorMsg = '您的用户待审核 请联系本文章创作者';
                            break;
                        default:
                            $errorCode = 'Null';
                            $errorMsg = '未知原因';
                            break;
                    }
                    return view('ErrorPage/Error', [
                        "errorCode" => $errorCode,
                        "errorTitle" => "发生意外错误 错误提示 ⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️",
                        "errorMsg" => $errorMsg,
                    ]);
                    exit();
                }
                if ($value["author_or_chinese_team"] == 0) { //判断是不是作者
                    if ($value["user_id"] == $user_info['_id']) {
                        $book_info['me_role'] = 'author'; //如果我是作者 设置角色为作者
                        $book_info['edit_delete_user'] = $value['edit_delete_user']; //如果我是协作者 设置我为协作者
                        $book_info['edit_add_user'] = $value['edit_add_user']; //是否允许新增用户 是否允许新增用户
                        $book_info['edit_sever_comics_info'] = $value['edit_sever_comics_info']; //是否允许新增用户 是否允许新增用户

                    }
                    $book_info['author_and_chinese_team'][$key]['authorOrChinese_team'] = '创建者';
                } else if ($value["author_or_chinese_team"] == 1) { //判断是不是协作者
                    if ($value["user_id"] == $user_info['_id']) {
                        $book_info['me_role'] = 'chinese_team'; //如果我是协作者 设置我为协作者
                        $book_info['edit_delete_user'] = $value['edit_delete_user']; //如果我是协作者 设置我为协作者
                        $book_info['edit_add_user'] = $value['edit_add_user']; //是否允许新增用户 是否允许新增用户
                        $book_info['edit_sever_comics_info'] = $value['edit_sever_comics_info']; //是否允许新增用户 是否允许新增用户

                    }
                    $book_info['author_and_chinese_team'][$key]['authorOrChinese_team'] = '协作者';
                }

                $hash_hmac_json = [
                    "hash_hmac_user_id" => hash_hmac("sha256", $value["user_id"] . $bookId . $time, config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")), //书籍用户id 加密后 加密id
                    "user_id" => $value["user_id"],
                    "time" => $time,
                    "_id" => $value["_id"],
                    "book_id" => $bookId,
                    "role" => $value["author_or_chinese_team"],
                ];
                $book_info['author_and_chinese_team'][$key]['hash_hmac_str'] = authcode(base64_encode(json_encode(json_decode(json_encode($hash_hmac_json)))), 'encode', config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption"));
            }
            //解析漫画分类
            $categories = [];
            $classified_catalogueList = Db::table('classified_catalogue')
                ->select();

            $me_categories = array();
            foreach (explode(',', $book_info["categories"]) as $categoriesKey => $categoriesValue) {
                $me_categories[$categoriesValue] = true;
            }
            foreach ($classified_catalogueList as $key => $value) {
                $classified_catalogue[$key] = [
                    "name" => $value["title"],
                    "value" =>  $value["_id"],
                    "selected" => (array_key_exists($value["title"], $me_categories)) ? true : false,
                ];
            }
            foreach (explode(',', $book_info["categories"]) as $categoriesKey => $categoriesValue) {
                array_push($categories, [
                    "name" => "$categoriesValue",
                    "value" => '$categoriesValue',
                ]);
            }
            //解析漫画分类
            //!解析漫画标签
            $comicsTag = explode(',', $book_info["tags"]);

            $ArrayComicsTagList = [];
            #全部数组
            //!初始化全部数据 会减慢运行速度很多
            $TagList = Db::table('tags')
                ->where(['state' => 1])
                ->field(["tag_name"])
                ->select();
            foreach ($TagList as $key => $value) {
                $ArrayComicsTagList[$value['tag_name']] = [
                    "name" => $value['tag_name'],
                    "value" => $value['tag_name'],
                ];
            }
            $SelectComicsTagList = [];
            //以选择数组

            foreach ($comicsTag as $key => $value) {
                $SelectComicsTagList[$value] = [
                    "name" => $value,
                    "value" => $value,
                    "selected" => true,
                ];
            }

            foreach ($SelectComicsTagList as $selectKey => $selectValue) {
                $ArrayComicsTagList[$selectValue['name']] = [
                    "name" => $selectValue['name'],
                    "value" => $selectValue['name'],
                    "selected" => true,
                ];
            }
            $ListComicsTagList = [];
            foreach ($ArrayComicsTagList as $key => $value) {
                array_push($ListComicsTagList, $value);
            }
            //!解析漫画标签
            if ($book_info['me_role'] == 'other') { //判断我在这篇文章的角色 如果是其他 不是作者 也不是协作者
                return view('ErrorPage/Error', [
                    "errorCode" => 2003,
                    "errorTitle" => "发生意外并且严重错误",
                    "errorMsg" => "不允许此用户操作 这是不允许的操作",
                ]);
            }
            return view('Edit/EditComicsInfo/EditComicsInfo', [
                "serverLocalhost" => config("globalsettings.serverLocalhost_serverHost"),
                "bookId" => $bookId,
                "bookInfo" => $book_info,
                "time" => $time,
                "hashHmac_bookId" => $hashHmac_bookId,
                "hashHmac_toKen" => $hashHmac_toKen, //加密用户id 加密方法 token+书籍id+时间戳
                "classified_catalogue" => json_encode($classified_catalogue), //分类
                "TagList" => json_encode($ListComicsTagList), //分类
                "user_info" => $user_info,
            ]);
        } else {
            return view('ErrorPage/Error', [
                "errorCode" => 2005,
                "errorTitle" => "发生严重错误",
                "errorMsg" => "这一个漫画id对应多个漫画请尝试修复 这是不允许的操作",
            ]);
        }
    }
    public function AddProject()
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $bookId = input('bookId');
        $projectName = input('title');
        $order = input('order');

        if ((float) $order == 0) {
            return errorJsonReturn('Missing parameter', '序号不正确');
        }
        $MyComicsState = Db::table('book_info')
            ->alias('book_info')
            ->where([
                "book_info._id" => $bookId,
                "author_and_chinese_team.user_id" => $user_info['_id']
            ])
            ->join('author_and_chinese_team author_and_chinese_team', 'author_and_chinese_team.book_id = book_info._id')
            ->order('author_and_chinese_team.id desc')
            ->field([
                "author_and_chinese_team.edit_delete_user",
                #允许删除用户
                "author_and_chinese_team.edit_inherit_users",
                #是否允许继承用户
                "author_and_chinese_team.edit_add_user",
                #增加用户
                "author_and_chinese_team.edit_edit_user",
                #编辑用户
                "author_and_chinese_team.edit_sever_comics_info",
                #是否允许保存修改漫画信息
                "author_and_chinese_team.edit_add_project",
                #是否允许添加章节
                #1允许添加 0不允许
                "author_and_chinese_team.state",
            ])
            ->find();
        if (!$MyComicsState) {
            //判断我的状态
            return errorJsonReturn('User permission error');
        }
        if ($MyComicsState['state'] != 0 || $MyComicsState['edit_add_project'] != 1) {
            //判断我的权限
            return errorJsonReturn('Insufficient user rights');
        }

        $insertID = randIdStructure(5, 128);
        $selectbook_info_project = Db::table('book_info_project')
            ->where([
                '_id' => $bookId,
                #书籍id
                'order' => $order,
                #分卷序列号
            ])
            ->count();
        if ($selectbook_info_project) {
            //判断要插入的分卷id是否存在
            return errorJsonReturn('Duplicate data already exists');
        }
        Db::table("book_info_project")
            #插入分类列表
            ->insert([
                '_id' => $bookId,
                #书籍id
                'project_title' => $projectName,
                #分卷名
                'order' => $order,
                #分卷序列号
                "updated_at" => date('Y-m-d H:i:s'),
                #发布时间
                "chapter_id" => $insertID,
                #分卷id
            ]);
        // 插入操作日志
        Db::table('log_book_info_project')
            ->insert([
                "_id" => $bookId,
                #书籍id
                "project_id" => $insertID,
                #分卷id 用于记录哪一个操作的
                "project_name" => $projectName,
                #分卷名
                "project_order" => $order,
                "msg" => "用户$user_info[_id]创建了此分卷",
            ]);
        return successJsonReturn([
            "bookId" => $bookId,
            "chapter_id" => $insertID,
            "title" => $projectName,
            "order" => $order,
            // "insert_user_id" => $user_info["_id"],
        ]);
    }
}
